<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/4/25 0025
 * Time: 10:03
 */

use Workerman\Worker;
require_once __DIR__ . './vendor/workerman/workerman/Autoloader.php';

// 注意：这里与上个例子不同，使用的是websocket协议
$ws_worker = new Worker("websocket://127.0.0.1:1935");
// 启动4个进程对外提供服务
$ws_worker->count = 4;

//有新的连接
$ws_worker->onConnect = function($connection) {
    $connection->uid = mt_rand(1,10);
    global $ws_worker;
    //把消息发送回所有连接的 client 上去
    foreach ($ws_worker->connections as $_connection ){
        $response = json_encode(array('type'=>'system', 'message'=> $connection->getRemoteIp().'---'.$connection->uid.' connected'));
        $_connection->send($response);
    }
};

// 当收到客户端发来的数据后返回hello $data给客户端
$ws_worker->onMessage = function($connection, $data) {
    global $ws_worker;
    $tst_msg = json_decode($data);
    $user_name = $tst_msg->name;
    $user_message = $tst_msg->message;

    //把消息发送回所有连接的 client 上去
    $response_text = json_encode(array('type'=>'usermsg', 'name'=>$user_name."--".$connection->uid, 'message'=>$user_message));
    // 向客户端发送$data
    foreach ( $ws_worker->connections as $_connection ){
        $_connection->send($response_text);
    }
};

// 用户断开链接
$ws_worker->onClose = function($connection) {
    global $ws_worker;
    //把消息发送回所有连接的 client 上去
    $response_text = json_encode(array('type'=>'system', 'message'=>$connection->getRemoteIp()."--".$connection->uid.' close'));
    // 向客户端发送$data
    foreach ( $ws_worker->connections as $_connection ){
        $_connection->send($response_text);
    }
};

// 运行worker
Worker::runAll();